package com.spice.common.util;


import com.spice.common.model.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author helen
 * @since 2019/10/16
 * @description token的生成、校验和信息提取工具类
 */
@Slf4j
public class JwtUtils {

    /**常量:token过期时间：24小时*/
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    /**常量:秘钥*/
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 生成token字符串的方法
     *
     * @param name 昵称
     * @return token字符串
     */
    public static String getJwtToken(String id, String name, String avatar, String status) {

        String jwtToken = Jwts.builder()
                // 设置头
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                // 设置有效载荷默认字段
                .setSubject("zjx-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                // 设置有效载荷主体部分 ，存储用户信息
                .claim("id", id)
                .claim("name", name)
                .claim("avatar", avatar)
                .claim("status", status)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return jwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return token是否有效
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            log.error("token校验出错", e);
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request http请求
     * @return token是否有效
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            log.error("token校验出错", e);
            return false;
        }
        return true;
    }

    /**
     * 根据token字符串获取用户name、avatar和status
     * @param token token字符串
     * @return 该请求用户的用户信息
     */
    public static UserInfo getUserInfoByJwtToken(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);

        Claims claims = claimsJws.getBody();
        String name = (String)claims.get("name");
        String avatar = (String) claims.get("avatar");
        String status = (String) claims.get("status");
        String id = (String) claims.get("id");

        return new UserInfo(id, name, avatar, status);
    }

    /**
     * 根据Http请求获取用户name、avatar和status
     * @return 该请求用户的用户信息
     */
    public static UserInfo getUserInfoByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("X-TOKEN");
        if(StringUtils.isEmpty(jwtToken)) {
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);

        Claims claims = claimsJws.getBody();
        String name = (String)claims.get("name");
        String avatar = (String) claims.get("avatar");
        String status = (String) claims.get("status");
        String id = (String) claims.get("id");

        return new UserInfo(id, name, avatar, status);
    }
}